<template>
  <div>
    <vxe-toolbar>
      <template #buttons>
        <el-button type="success" icon="el-icon-plus" size="medium" @click="insertEvent">新增记录</el-button>
        <!-- <el-button type="success" icon="el-icon-printer" size="medium" @click="printEvent">打印</el-button> -->
        <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
      </template>
    </vxe-toolbar>
    <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row :loading="loading" :data="dataList" @sort-change="sortChange">
      <vxe-table-column field="name" title="论文题目" sortable></vxe-table-column>
      <vxe-table-column field="publishDate" title="发表时间" sortable></vxe-table-column>
      <vxe-table-column field="periodicalName" title="发表刊物" sortable></vxe-table-column>
      <vxe-table-column field="result" title="成绩" sortable></vxe-table-column>
      <vxe-table-column field="issn" title="国际标准期刊编号" sortable></vxe-table-column>
      <vxe-table-column field="writerRankName" title="第几作者" sortable></vxe-table-column>
      <vxe-table-column field="total" title="总人数" sortable></vxe-table-column>
      <vxe-table-column field="publishType" title="发行类型" sortable></vxe-table-column>
      <vxe-table-column field="code" title="邮发代码" sortable></vxe-table-column>
      <vxe-table-column field="isOnNetName" title="网上查询" sortable></vxe-table-column>
      <vxe-table-column field="useCase" title="录用情况" sortable></vxe-table-column>
      <vxe-table-column field="subjectLevel" title="课题级别" sortable></vxe-table-column>
      <vxe-table-column field="rank" title="名次" sortable></vxe-table-column>
      <vxe-table-column field="wordCount" title="字数" sortable></vxe-table-column>
      <vxe-table-column field="" title="操作" width="110">
        <template #default="{ row,rowIndex }">
          <el-button @click="editEvent(row,rowIndex)" type="success" size="medium" icon="el-icon-edit" circle></el-button>
          <el-button @click="deleteEvent(row)" type="danger" size="medium"  icon="el-icon-delete" circle></el-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
      :total="page.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
      @page-change="handlePageChange">
    </vxe-pager>
    <vxe-modal v-model="insertModal" title="学术论文著作">
      <template #default>
         <el-form inline-message ref="insertForm" :rules="rules" :model="insertForm" label-width="130px">
           <el-form-item label="论文题目" prop="name">
             <el-input v-model="insertForm.name"></el-input>
           </el-form-item>
           <el-form-item label="发表时间" prop="publishDate">
             <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.publishDate" style="width: 100%;"></el-date-picker>
           </el-form-item>
           <el-form-item label="发表刊物">
             <el-select v-model="insertForm.periodical" filterable clearable style="width: 100%;" placeholder="请选择">
               <el-option :label="item" :value="key" v-for="(item,key,index) in dict_periodical" :key="index"></el-option>
             </el-select>
           </el-form-item>
           <el-form-item label="成绩">
             <el-input v-model="insertForm.result"></el-input>
           </el-form-item>
           <el-form-item label="国际标准期刊编号">
             <el-input v-model="insertForm.issn"></el-input>
           </el-form-item>
           <el-form-item label="第几作者">
             <el-select v-model="insertForm.writerRank" filterable clearable style="width: 100%;" placeholder="请选择">
               <el-option :label="item" :value="key" v-for="(item,key,index) in dict_writerRank" :key="index"></el-option>
             </el-select>
           </el-form-item>
           <el-form-item label="总人数">
             <el-input v-model.number="insertForm.total" type="number"></el-input>
           </el-form-item>
           <el-form-item label="发行类型">
             <el-select v-model="insertForm.publishTypeId" filterable clearable style="width: 100%;" placeholder="请选择">
               <el-option :label="item" :value="key" v-for="(item,key,index) in dict_publishType" :key="index"></el-option>
             </el-select>
           </el-form-item>
           <el-form-item label="邮发代码">
             <el-input v-model="insertForm.code"></el-input>
           </el-form-item>
           <el-form-item label="网上查询">
             <el-select v-model="insertForm.isOnNet" filterable clearable style="width: 100%;" placeholder="请选择">
               <el-option :label="item" :value="key" v-for="(item,key,index) in dict_isOnNet" :key="index"></el-option>
             </el-select>
           </el-form-item>
           <el-form-item label="录用情况">
             <el-select v-model="insertForm.useCaseId" filterable clearable style="width: 100%;" placeholder="请选择">
               <el-option :label="item" :value="key" v-for="(item,key,index) in dict_useCase" :key="index"></el-option>
             </el-select>
           </el-form-item>
           <el-form-item label="课题级别">
             <el-select v-model="insertForm.subjectLevelId" filterable clearable style="width: 100%;" placeholder="请选择">
               <el-option :label="item" :value="key" v-for="(item,key,index) in dict_subjectLevel" :key="index"></el-option>
             </el-select>
           </el-form-item>
           <el-form-item label="名次">
             <el-select v-model="insertForm.rankId" filterable clearable style="width: 100%;" placeholder="请选择">
               <el-option :label="item" :value="key" v-for="(item,key,index) in dict_rank" :key="index"></el-option>
             </el-select>
           </el-form-item>
           <el-form-item label="字数">
             <el-select v-model="insertForm.wordCountId" filterable clearable style="width: 100%;" placeholder="请选择">
               <el-option :label="item" :value="key" v-for="(item,key,index) in dict_wordCount" :key="index"></el-option>
             </el-select>
           </el-form-item>
           <el-form-item>
               <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
               <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">保存</el-button>
           </el-form-item>
         </el-form>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {person_paper,person_paper_insert,person_paper_update,person_paper_delete} from '@/api/person.js'
  export default{
    props:['pId'],
    data() {
      return {
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        dict_periodical: {1: '学术刊物', 2: '其他'},
        dict_writerRank: {
          1: '1',
          2: '2',
          3: '3',
          4: '4',
          5: '5',
        },
        dict_publishType: {
          1: "公开发行",
        },
        dict_isOnNet: {
          1: "是",
          2: "否",
          3: "不详",
        },
        dict_useCase: {
          1: "二级及以上学术论文报告会录用论文",
          2: "参加厅局级以上课题或研究项目",
          3: "公开出版的学术著作或教材",
        },
        dict_subjectLevel: {
          1: "省部级",
          2: "厅局级",
        },
        dict_rank: {
          1: "第一名",
          2: "第二名",
          3: "第三名",
          4: "第四名",
          5: "第五名",
        },
        dict_wordCount: {
          1: "两万字及以上",
          2: "少于两万字",
        },
        filterName: '',
        insertModal: false,
        insertForm: {
          name: '',
          publishDate: '',
          result: '',
          code: '',
          publishTypeId: '',
          subjectLevelId: '',
          wordCountId: '',
          rankId: '',
          useCaseId: '',
          isOnNet: '',
          issn: '',
          writerRank: '',
          periodical: '',
          total: '',
        },
        sportItemData: [],
        rules: {
          name: [
            { required: true, message: '这是必填项', trigger: 'blur' },
          ],
          publishDate: [
            { required: true, message: '这是必填项', trigger: 'blur' },
          ],
        },
        isInsert: true,
        paperId: '',
        search: false,
        currentIndex: null,
      }
    },
    created() {
      this.person_paper()
    },
    computed: {
      openDateValid() {
        if(this.insertForm.openDate && this.insertForm.closeDate){
          if(this.insertForm.openDate > this.insertForm.closeDate) {
            this.$message.error('开始时间必须小于结束时间！')
            return false
          }else{
            return true
          }
        }else{
          return true
        }
      }
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          person_paper_delete({pId:this.pId,data:{paperId:row.paperId}}).then(res=>{
            if(res.code === 200 ) {
              this.defaultDataList.forEach((item,index)=>{
              	if(item.paperId == row.paperId){
              	  this.defaultDataList.splice(index,1)
              	}
              })
              this.init_data(this.defaultDataList)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      editEvent(row,rowIndex) {
        this.currentIndex = rowIndex
        this.paperId = row.paperId
        this.insertForm.name = row.name
        this.insertForm.publishDate = row.publishDate+''
        this.insertForm.result = row.result
        this.insertForm.code = row.code
        this.insertForm.publishTypeId = row.publishTypeId==0?'':row.publishTypeId+''
        this.insertForm.subjectLevelId = row.subjectLevelId==0?'':row.subjectLevelId+''
        this.insertForm.wordCountId = row.wordCountId==0?'':row.wordCountId+''
        this.insertForm.rankId = row.rankId==0?'':row.rankId+''
        this.insertForm.useCaseId = row.useCaseId==0?'':row.useCaseId+''
        this.insertForm.isOnNet = row.isOnNet==0?'':row.isOnNet+''
        this.insertForm.issn = !row.issn?'':row.issn
        this.insertForm.writerRank = row.writerRank==0?'':row.writerRank+''
        this.insertForm.periodical = row.periodical!=0?row.periodical==0?'':row.periodical:''
        this.insertForm.total = row.total==0?'':row.total+''
        this.isInsert = false
        this.insertModal = true
      },
      insertSave() {
        this.$refs.insertForm.validate((valid) => {
          if (valid && this.openDateValid) {
            let data = {}
            if(this.insertForm.publishDate) data.publishDate = this.$moment(this.insertForm.publishDate).format('YYYY-MM-DD')+' 00:00:00'
            if(this.insertForm.name) data.name = this.insertForm.name
            if(this.insertForm.result) data.result = this.insertForm.result
            if(this.insertForm.code) data.code = this.insertForm.code
            if(this.insertForm.publishTypeId) data.publishTypeId = this.insertForm.publishTypeId
            if(this.insertForm.subjectLevelId) data.subjectLevelId = this.insertForm.subjectLevelId
            if(this.insertForm.wordCountId) data.wordCountId = this.insertForm.wordCountId
            if(this.insertForm.rankId) data.rankId = this.insertForm.rankId
            if(this.insertForm.useCaseId) data.useCaseId = this.insertForm.useCaseId
            if(this.insertForm.isOnNet) data.isOnNet = this.insertForm.isOnNet
            if(this.insertForm.issn) data.issn = this.insertForm.issn
            if(this.insertForm.writerRank) data.writerRank = this.insertForm.writerRank
            if(this.insertForm.periodical) data.periodical = this.insertForm.periodical
            if(this.insertForm.total) data.total = this.insertForm.total
            data.pId = this.pId
            if(this.isInsert){
              person_paper_insert(data).then(res=>{
                if(res.code === 200) {
                  this.dataList.unshift(res.data)
                  this.defaultDataList.push(res.data)
                  this.init_data(this.defaultDataList)
                  this.page.totalResult+=1
                  this.$refs.XTable.setCurrentRow(this.dataList[0])
                  this.$message.success('保存成功')
                  this.insertSuccess = true
                  this.insertModal = false
                }else{
                  this.$message.error(res.message)
                }
              })
            }else{
              data.paperId = this.paperId
              person_paper_update(data).then(res=>{
                if(res.code === 200) {
                  Object.assign(this.dataList[this.currentIndex],res.data)
                  this.defaultDataList.forEach(item=>{
                  	if(res.data.paperId == item.paperId){
                  	  Object.assign(item,res.data)
                  	}
                  })
                  this.init_data(this.defaultDataList)
                  this.$message.success('修改成功')
                  this.insertModal = false
                }else{
                  this.$message.error(res.message)
                }
              })
            }
          } else {
            return false;
          }
        })
      },
      insertEvent() {
        this.insertForm = {
          name: '',
          publishDate: '',
          result: '',
          code: '',
          publishTypeId: '',
          subjectLevelId: '',
          wordCountId: '',
          rankId: '',
          useCaseId: '',
          isOnNet: '',
          issn: '',
          writerRank: '',
          periodical: '',
          total: '',
        }
        this.isInsert = true
        this.insertModal = true
      },
      sportChange() {
        this.insertForm.sportItemId = ''
        sport_item_by_sportId({sportId:this.insertForm.sportId}).then(res=>{
          if(res.code === 200) {
            this.sportItemData = res.data
          }
        })
      },
      printEvent() {
        let topHtml = '<h2>学术论文著作</h2>'
        this.searchEvent()
        setTimeout(()=>{
          this.$refs.XTable.print({
              sheetName: '学术论文著作',
              beforePrintMethod: ({content}) => {
                  return topHtml + content
              }
          })
        },1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
            }
            this.search = true
        } else {
          this.dataList = this.defaultDataList
        }
      },
      person_paper() {
        person_paper(this.pId).then(res=>{
          if(res.code === 200 && res.data.length != 0) {
            let data = res.data
            this.init_data(data)
            this.$emit('empPaperDataPrint',this.defaultDataList)
          }else{
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        let dict_isOnNet = {1:'是',2:'否',3:'不详'}
        data.forEach(item=>{
          item.publishDate = this.$moment(item.publishDate).format('YYYY-MM-DD') == 'Invalid date'?'':this.$moment(item.publishDate).format('YYYY-MM-DD')
          item.periodicalName = this.dict_periodical[item.periodical]
          item.writerRankName = this.dict_writerRank[item.writerRank]
          item.publishType = this.dict_publishType[item.publishTypeId]
          item.isOnNetName = this.dict_isOnNet[item.isOnNet]
          item.useCase = this.dict_useCase[item.useCaseId]
          item.subjectLevel = this.dict_subjectLevel[item.subjectLevelId]
          item.rank = this.dict_rank[item.rankId]
          item.wordCount = this.dict_wordCount[item.wordCountId]
          item.total = item.total==0?'':item.total
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      handlePageChange({currentPage,pageSize}) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
